package com.springboot.springbootlogindemo.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.maxmind.geoip2.exception.GeoIp2Exception;
import com.springboot.springbootlogindemo.DTO.UserDTO;
import com.springboot.springbootlogindemo.domain.UserInfo;
import com.springboot.springbootlogindemo.service.SongListService;
import com.springboot.springbootlogindemo.service.SongService;
import com.springboot.springbootlogindemo.service.UserInfoService;
import com.springboot.springbootlogindemo.service.UserService;
import com.springboot.springbootlogindemo.utils.Result;
import com.springboot.springbootlogindemo.utils.*;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import static com.springboot.springbootlogindemo.utils.Geo.changeAddress;


/**
 *
 */


@RestController//表明此类是一个控制器类,且返回的不是视图，而是数据
@RequestMapping("/user")//控制器类的基路由
public class UserController {
    @Resource
    private UserService userService;

    @Resource
    private UserInfoService userInfoService;

    @Resource
    private SongListService songListService;

    @Resource
    private SongService songService;


    /**
     * 发送验证码
     * @param phone
     * @return
     */
    @PostMapping("/sendCode")//表示处理post请求，路由是register
    public Result sendCode(@RequestParam String phone){
        return userService.sendCode(phone);
    }

    /**
     * 登录，若没有账号，则注册并登录
     * @param phone
     * @param code
     * @return
     */
    @PostMapping("/loginWithRegister")//表示处理post请求，路由是register
    public Result loginController(@RequestParam String phone,@RequestParam String code){
        return userService.loginWithRegister(phone,code);
    }


    /**
     * 从DB获取用户信息
     * @return
     */
    @GetMapping("/meFromBd")
    public Result meFormDb(){
        return userService.getUser();
    }

    /**
     * 从后台获取用户信息
     * @return
     */
    @GetMapping("/meNow")
    public Result meNow(){
        // TODO 获取当前登录的用户并返回
        UserDTO userDTO= UserHolder.getUser();
        return Result.success(userDTO);
    }

    /**
     * 设置个人信息页面
     * @param userInfo
     * @return
     */
    @PostMapping("/setProfile")
    public Result setProfile(@RequestBody UserInfo userInfo){
        return userInfoService.updateProfile(userInfo);
    }

    /**
     * 获取个人信息
     * @return
     */
    @GetMapping("/getProfile")
    public Result getProfile(){
        return userInfoService.getProfile();
    }








    //判断验证码同时判断该用户是否存在,这里是通过session实现的，但是session存在同源策略问题。假如用token的话，需要从后台验证码拿出来，这个验证码去哪里拿？redis拿哦
//    @PostMapping("/judgeVerifyCode")
//    public Result<User> judgeVerifyCodeController(@RequestParam String VerifyCode,HttpServletRequest request){
//        //获得session
//        HttpSession session =request.getSession();
//        String telephone=(String)session.getAttribute("telephone");
//        //验证验证码和用户
//        User user=userDao.findByTelephone(telephone);
////        User user=userService.getUserByTelephone(telephone);
//        if(session.getAttribute("verifyCode").equals(VerifyCode)&&userService.telephoneVerifyService(telephone)){
//            session.setAttribute("userName",user.getUname());
//            String token=JwtUtil.createToken(user);
//            return Result.success(user,token);
//        }
//        else{
//            return Result.error("123","验证错误");
//        }
//    }


//    /**
//     * 发送短信
//     * @param request
//     * @return
//     */
//    @RequestMapping(value = "/smsXxs")//没有请求要求，获得get或者post或者其他所有请求
//    @ResponseBody
//    //从前端获得一个请求,因为这里是请求找回密码，所以这个request回来的时候是不携带session的其实
//    public Map<String,Object> smsXxs(String phone, HttpServletRequest request) throws ClientException {
//        Map<String,Object> map = new HashMap<>();
//        //建立一个hashmap
//        // 验证码（指定长度的随机数）
//        String code = CodeUtil.generateVerifyCode(6);//获得一个六位的验证码
//        String TemplateParam = "{\"code\":\""+code+"\"}";
//        // 短信模板id
//        String TemplateCode = "SMS_154950909";
//        //调用接口
//        SendSmsResponse response = SmsTool.sendSms(phone,TemplateParam,TemplateCode);
//        map.put("verifyCode",code);//存放key-value
//        map.put("phone",phone);//存放key-value
//        //session 其实也就像一个map，下面CodePhone是key，map就是value
//    //    request.getSession().setAttribute("CodePhone",map);
//        HttpSession session=request.getSession();
//        session.setAttribute("verifyCode",code);
//        session.setAttribute("telephone",phone);
//        if( response.getCode().equals("OK")) {
//            map.put("isOk","OK");
//        }
//        return map;
//    }
//    //登录后更改密码
//    @PostMapping("updatePassword")
//    public Result<User> updatePasswordController(@RequestParam String newPassword, HttpServletRequest request){
//        String uname=request.getAttribute("uname").toString();
//        User user =userService.updatePasswordService(uname,newPassword);
//        if(user!=null){
//            return Result.success(user,"修改成功!");
//        }
//        else {
//            return Result.error("123", "未知错误");
//        }
//    }
//    //登录后实现更改账号
//    @PostMapping("updateUName")
//    public Result<User> updateUNameController(@RequestParam String newuname,HttpServletRequest request){
//        String uname=request.getAttribute("uname").toString();
//        User user=userService.updateUNameService(uname,newuname);
//        if(user!=null){
//            return Result.success(user,"账号修改成功!");
//        }
//        else {
//            return Result.error("123", "用户名已存在");
//        }
//    }

//    //拿到图片，然后保存图片地址到数据库
//    @RequestMapping(value = "Manage/upBusinessImage",method = RequestMethod.POST)
//    public Result uploadBusinessImage(@RequestParam(value = "file", required = false) MultipartFile file,HttpServletRequest request) {
//        String uname=request.getAttribute("uname").toString();
//        String filename=fileService.uploadImage(file,"C:/static/avatar/").getMsg();
//        User user=userService.updateImgService(uname,"http://waczj.cn:8081/avatar/"+filename);
//        if(user!=null){
//            return Result.success(user,"头像保存成功");
//        }
//        else{
//            return Result.error("123","头像保存失败");
//        }
//    }

    @RequestMapping(value = "getAddress",method = RequestMethod.POST)
    public Result getAddress(HttpServletRequest request,String lat,String lng) throws IOException, GeoIp2Exception {
        //String address=Geo_1(request.getHeader("X-FORWARDED-FOR "));//121.43.161.169//60.191.122.35
        String change=changeAddress(lat,lng);
        JSONObject jsonObject= JSON.parseObject(change);
        JSONArray jsonArray = jsonObject.getJSONArray("locations");

        JSONObject jso = jsonArray.getJSONObject(0);

        String ass  = Geo.getAddress(jso.getString("lat"),jso.getString("lng"),"XS3BZ-2MGWG-W4ZQN-QSFMX-NJGG7-WFBHQ");
        JSONObject jsonObjects = JSON.parseObject(ass);
        JSONObject jsonArray1 =  jsonObjects.getJSONObject("result");
        JSONObject jsonObject1 =  jsonArray1.getJSONObject("formatted_addresses");
        JSONObject jsonObject2 = jsonArray1.getJSONObject("address_component");
        String address_1 =  ""+jsonObject2.getString("province")+""+jsonObject2.getString("city")+""+jsonObject2.getString("district")+""+
                jsonObject1.getString("rough");
        return  Result.success(address_1);
    }




}
